package com.example.mediaplayerpractice_1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.Toolbar;

import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    //MediaPlayer
    private MediaPlayer mediaplayer = new MediaPlayer();
    //Ui
    private Button buttonPlay;
    private Button buttonPause;
    private Button buttonStop;
    //动态申请权限；
    private static String[] PERMISSIONS = {
            "android.permission.WRITE_EXTERNAL_STORAGE",
            "android.permission.READ_EXTERNAL_STORAGE"
    };
    static boolean FLAG_PERMISSIONS = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initUI();
        if(!FLAG_PERMISSIONS){// 权限没有获取的时候就检查权限
            checkPermission();
        }
        mediaplayer = MediaPlayer.create(getApplicationContext(),R.raw.music);
        mediaplayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                initMusicPlayer();
            }
        });
        mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
            }
        });
    }

    private void checkPermission() {
        //进行权限查询，这个和之前的ContentProvider中的权限申请，很像，可参考！
        for(String permission : PERMISSIONS){
            if(ContextCompat.checkSelfPermission(MainActivity.this,permission) != PackageManager.PERMISSION_GRANTED ){
                //审查权限
                ActivityCompat.requestPermissions(this,PERMISSIONS,1);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 1:
                    for (int grantResult : grantResults){
                        if(grantResult != PackageManager.PERMISSION_GRANTED){
                            FLAG_PERMISSIONS = false;
                            Toast.makeText(getApplicationContext(),"Permisson is denied!",Toast.LENGTH_SHORT).show();
                            break;
                        }
                    }
                    FLAG_PERMISSIONS = true;
                break;
        }
    }

    private void initMusicPlayer() {
//        File file = new File(Environment.getExternalStorageDirectory(),"music.mp3");//这个是读取外部中的文件（即手机中文件）
        try {
//            mediaplayer.setDataSource(file.getAbsolutePath());
            mediaplayer = MediaPlayer.create(getApplicationContext(),R.raw.music);//这段代码主要体现的是在IDE中直接读取自带的文件,它直接调用prepare方法
//            mediaplayer.prepare();//准备媒体
        } catch (Exception e ) {
            e.printStackTrace();
            Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
        }
    }

    private void initUI() {
        buttonPlay = findViewById(R.id.button_play);
        buttonPause = findViewById(R.id.button_pause);
        buttonStop = findViewById(R.id.button_stop);
        buttonPause.setOnClickListener(this);
        buttonStop.setOnClickListener(this);
        buttonPlay.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_play:
                if(!mediaplayer.isPlaying()){
                    mediaplayer.start();
                    Toast.makeText(getApplicationContext(),"Playing",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.button_pause:
                if(mediaplayer.isPlaying()){
                    mediaplayer.pause();
                    Toast.makeText(getApplicationContext(),"Pausing",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.button_stop:
                if (mediaplayer.isPlaying()){
                    mediaplayer.stop();
                    Toast.makeText(getApplicationContext(),"Stopping",Toast.LENGTH_SHORT).show();
                    initMusicPlayer();
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mediaplayer != null){
            mediaplayer.stop();
            mediaplayer.release();
        }
    }
}